package com.sunyard.utils;

import org.bouncycastle.jce.provider.BouncyCastleProvider;
import org.bouncycastle.pqc.math.linearalgebra.ByteUtils;

import javax.crypto.Cipher;
import javax.crypto.KeyGenerator;
import javax.crypto.spec.SecretKeySpec;
import java.security.Key;
import java.security.SecureRandom;
import java.security.Security;
import java.util.Arrays;

/**
 * 工具类
 */
public class Sm4Util {

    static {
        Security.addProvider(new BouncyCastleProvider());
    }

    private static final String ENCODING = "utf-8";
    public static final String ALGORITHM_NAME = "SM4";

    //加密算法/分组加密模式/分组填充方式
    //PKCS5Padding-以八个字节为一组进行分组加密
    //定义分组加密模式使用：PKCS5Padding
    public static final String ALGORITHM_NAME_ECB_PADDING = "SM4/ECB/PKCS5Padding";
    //128-32位16进制；256-64位16进制
    public static final int DEFAULT_KEY_SIZE = 128;

    /**
     * 生成ECB暗号，加密解密通过mode表示
     *
     * @param algorithmName 算法名称
     * @param mode          模式
     * @param key
     * @return
     * @throws Exception
     * @explain ECB模式（电子密码本模式：Electronic codebook）
     */
    private static Cipher generateEcbCipher(String algorithmName, int mode, byte[] key) throws Exception {
        Cipher cipher = Cipher.getInstance(algorithmName, BouncyCastleProvider.PROVIDER_NAME);
        Key sm4Key = new SecretKeySpec(key, ALGORITHM_NAME);
        cipher.init(mode, sm4Key);
        return cipher;
    }

    /**
     * 生成默认长度密钥
     *
     * @return
     * @throws Exception
     */
    public static String generateKey() throws Exception {
        return generateKey(DEFAULT_KEY_SIZE);
    }

    /**
     * 生成自定义长度密钥
     *
     * @param keySize
     * @return
     * @throws Exception
     */
    public static String generateKey(int keySize) throws Exception {
        KeyGenerator kg = KeyGenerator.getInstance(ALGORITHM_NAME, BouncyCastleProvider.PROVIDER_NAME);
        kg.init(keySize, new SecureRandom());
        return ByteUtils.toHexString(kg.generateKey().getEncoded());
    }

    /**
     * sm4加密
     *
     * @param hexkey
     * @param paramStr
     * @return
     * @throws Exception
     */
    public static String encryptEcb(String hexkey, String paramStr) throws Exception {
        String cipherText = "";
        //16进制字符串转byte[]
        byte[] keyData = ByteUtils.fromHexString(hexkey);
        //String 转 byte[]
        byte[] srcData = paramStr.getBytes(ENCODING);
        //加密后的数组
        byte[] cipherArray = encrypt_Ecb_Padding(keyData, srcData);
        //byte[] 转 hexString
        cipherText = ByteUtils.toHexString(cipherArray);
        return cipherText;
    }

    /**
     * 加密模式之Ecb
     *
     * @param key  密钥byte数组
     * @param data 明文byte数组
     * @return
     * @throws Exception
     */
    public static byte[] encrypt_Ecb_Padding(byte[] key, byte[] data) throws Exception {
        //encrypt_mode 代表加密模式
        Cipher cipher = generateEcbCipher(ALGORITHM_NAME_ECB_PADDING, Cipher.ENCRYPT_MODE, key);
        return cipher.doFinal(data);
    }

    /**
     * 解密
     *
     * @param hexKey     密钥
     * @param cipherText 密文
     * @return
     * @throws Exception
     */
    public static String decryptEcb(String hexKey, String cipherText) throws Exception {
        //空串接受解密后数据
        String decryptStr = "";
        //密钥转数组
        byte[] keyData = ByteUtils.fromHexString(hexKey);
        //密文转数组
        byte[] cipherData = ByteUtils.fromHexString(cipherText);
        //调用decrypt_Ecb_Padding完成解密
        byte[] scrData = decrypt_Ecb_Padding(keyData, cipherData);
        //数组转字符串并接收
        decryptStr = new String(scrData, ENCODING);
        //返回解密后数据
        return decryptStr;
    }

    /**
     * 解密模式之ecb
     *
     * @param key        密钥byte数组
     * @param cipherText 密文byte数组
     * @return
     * @throws Exception
     */
    public static byte[] decrypt_Ecb_Padding(byte[] key, byte[] cipherText) throws Exception {
        //Cipher.DECRYPT_MODE，解密模式
        Cipher cipher = generateEcbCipher(ALGORITHM_NAME_ECB_PADDING, Cipher.DECRYPT_MODE, key);
        return cipher.doFinal(cipherText);
    }

    /**
     * 密钥 密文 明文 进行校验是否三方对应（通过密钥对密文解密后与明文直接对比）
     *
     * @param hexKey     密钥
     * @param cipherText 密文
     * @param paramStr   明文
     * @return
     * @throws Exception
     */
    public static boolean verifyEcb(String hexKey, String cipherText, String paramStr) throws Exception {
        //用于接受校验结果
        boolean flag = false;
        //hexString -- > byte[]
        byte[] keyData = ByteUtils.fromHexString(hexKey);
        //十六进制字符串转换成数组
        byte[] cipherData = ByteUtils.fromHexString(cipherText);
        //解密
        byte[] decryptData = decrypt_Ecb_Padding(keyData, cipherData);
        //将原字符串转换成byte[]
        byte[] srcData = paramStr.getBytes(ENCODING);
        //判断两个数组是否一致
        flag = Arrays.equals(decryptData, srcData);
        return flag;
    }

    public static void main(String[] args) throws Exception {
        String str = "B6BCC818082198DFA930516FEA880037E64BCC255BC98A296673EE03BE5A8F56485B9AEA888DC7EE054E8C0F201421894157368D8C83DD2A8E976A426600BD35";
        String KEY = "78841267D2B65AC9616CB8FD32C81621";
        String s = decryptEcb(KEY, str);
        System.out.println(s);
    }
}
